package com.jacky.iot.handlers;

import com.google.gson.Gson;
import com.jacky.iot.commons.Cmd;
import com.jacky.iot.dtos.WebSocketReq;
import com.jacky.iot.service.WebSocketFetchDataService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;


@Service
public class IotWebSocketHandler extends TextWebSocketHandler {

    private final static Logger LOG = LoggerFactory.getLogger(IotWebSocketHandler.class);
    private final Gson gson;

    private final WebSocketFetchDataService fetchDataService;

    public IotWebSocketHandler(Gson gson, WebSocketFetchDataService fetchDataService) {
        this.gson = gson;
        this.fetchDataService = fetchDataService;
    }

    /**
     * 新建连接
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        String path = session.getUri().getPath();
        LOG.info("新建连接 path:{}", path);
    }

    /**
     * 收到消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        WebSocketReq wsr = messageParse(message);
        if (isFetchData(wsr.getCmd())) {
            fetchDataService.handleDataFetch(session, wsr);
        }
        LOG.info("收到新消息:{}", message.getPayload());
    }

    /**
     * 连接关闭
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        fetchDataService.handleSessionClose(session);
        LOG.info("断开连接:");
    }

    private boolean isFetchData(Cmd cmd) {
        return cmd != null && (cmd.equals(Cmd.FETCH_DATA) || cmd.equals(Cmd.UPDATE_FETCH_INTERVAL) || cmd.equals(Cmd.CANCEL_FETCH_DATA));
    }

    private WebSocketReq messageParse(TextMessage message) {
        String payload = message.getPayload();
        if (StringUtils.isBlank(payload)) {
            return new WebSocketReq();
        }
        return gson.fromJson(payload, WebSocketReq.class);
    }
}
